import subprocess
import json
import re

def get_ip6_addresses():
    # 执行 ip -6 addr show scope global 命令并获取输出
    result = subprocess.run(['ip', '-6', 'addr', 'show', 'scope', 'global'], capture_output=True, text=True)

    # 正则表达式匹配网络接口和IP地址
    interface_pattern = re.compile(r'^\d+: (\S+):')
    address_pattern = re.compile(r'\s+inet6 ([a-f0-9:]+/\d+) scope (\S+) dynamic')
    lifetimes_pattern = re.compile(r'\s+valid_lft (\d+)sec preferred_lft (\d+)sec')

    # 结果存储
    interfaces = []

    # 当前接口
    current_interface = None

    # 逐行解析命令输出
    lines = result.stdout.splitlines()
    i = 0
    while i < len(lines):
        line = lines[i]
        
        # 匹配接口名
        interface_match = interface_pattern.match(line)
        if interface_match:
            if current_interface:
                interfaces.append(current_interface)
            current_interface = {
                'name': interface_match.group(1),
                'state': 'UP' if 'UP' in line else 'DOWN',  # 状态可以根据需要进一步完善
                'mtu': int(re.search(r'mtu (\d+)', line).group(1)) if 'mtu' in line else None,
                'addresses': []
            }
            i += 1
            continue

        # 匹配 IPv6 地址
        address_match = address_pattern.match(line)
        if address_match and current_interface:
            address = address_match.group(1)
            scope = address_match.group(2)
            
            # 提取 valid_lft 和 preferred_lft
            valid_lft = None
            preferred_lft = None
            
            # 检查下一行是否包含 valid_lft 和 preferred_lft 信息
            if i + 1 < len(lines):
                next_line = lines[i + 1]
                lifetimes_match = lifetimes_pattern.match(next_line)
                if lifetimes_match:
                    valid_lft = int(lifetimes_match.group(1))
                    preferred_lft = int(lifetimes_match.group(2))
            
            current_interface['addresses'].append({
                'inet6': address,
                'scope': scope,
                'dynamic': True,     # 默认动态地址
                'valid_lft': valid_lft,
                'preferred_lft': preferred_lft
            })

        i += 1

    # 将最后一个接口添加到列表
    if current_interface:
        interfaces.append(current_interface)

    # 转换为 JSON 格式并返回
    return json.dumps({"interfaces": interfaces}, indent=2)

# 调用函数并输出结果
if __name__ == '__main__':
    result = get_ip6_addresses()
    print(result)
